import React, { useRef, useEffect, useState } from "react";
import igv from "../plugins/igv/dist/igv.esm.js";

interface BigWigUrlListProps {
    type: string;
    format: string;
    name: string;
    url: string;
}

interface BigWigViewerProps {
    bigWigUrlList: any[];
    genome?: string;
    locus?: string;
}

const BigWigViewer: React.FC<BigWigViewerProps> = ({
    bigWigUrlList,
    genome = "hg38",
    locus,
}) => {
    const igvContainer = useRef(null);
    const browserInstance = useRef<any>(null);
    const [igvLoaded, setIgvLoaded] = useState(false);

    useEffect(() => {
        if (!igvContainer.current || browserInstance.current) {
            return;
        }

        console.log("Creating IGV browser instance...");
        const options = {
            genome,
            tracks: bigWigUrlList,
            // 第一次创建时，locus 使用初始值
            locus,
        };

        igv.createBrowser(igvContainer.current, options)
            .then((browser) => {
                browserInstance.current = browser;
                setIgvLoaded(true);
                console.log("IGV browser created successfully.");
            })
            .catch((e) => {
                console.error("Error creating IGV browser:", e);
            });

        return () => {
            if (browserInstance.current && browserInstance.current.destroy) {
                console.log("Component unmounting, destroying IGV instance.");
                browserInstance.current.destroy();
                browserInstance.current = null;
            }
        };
    }, [bigWigUrlList, genome]); // 注意：这里没有 locus

    // 负责在 locus 变化时更新浏览器视图
    useEffect(() => {
        if (browserInstance.current && locus) {
            try {
                browserInstance.current.search(locus);
                console.log("IGV locus updated to:", locus);
            } catch (error) {
                console.error("Error updating IGV locus:", error);
            }
        }
    }, [locus]);

    return (
        <div ref={igvContainer} className="h-[360px] m-5 bg-gray-100">
            {!igvLoaded && (
                <p className="text-gray-500 text-center mt-20">
                    Loading IGV Viewer...
                </p>
            )}
        </div>
    );
};

export default BigWigViewer;
export type { BigWigUrlListProps };
